package com.jd.xubobo.bookshow.service;

import com.jd.xubobo.bookshow.dao.BookMapper;
import com.jd.xubobo.bookshow.domain.Book;
import com.jd.xubobo.bookshow.domain.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private Page bookPage;      //一般这种不进行注入，因为不同的东西可能不要不同的page。

    //分页展示书籍列表
    public List<Book> bookListByPage(int page) {
        bookPage.setItems(bookMapper.getBookNum());
        bookPage.setPage(page);
        List<Book> books = bookMapper.bookListByPage(bookPage.getOffset(), bookPage.getLength());
        return books;
    }

    //获得下一页书籍列表，如果是最后一页，下一页还是最后一页
    public List<Book> nextPage(){
        return bookListByPage(bookPage.getNextPage());
    }

    //获得上一页书籍列表，如果是第一页，上一页还是第一页
    public List<Book> previousPage(){
        return bookListByPage(bookPage.getPreviousPage());
    }

    //获得最后一页书籍列表
    public List<Book> lastPage(){
        return bookListByPage(bookPage.getLastPage());
    }

    //根据书籍ID查询书籍
    public Book findById(long id) {
        return bookMapper.findById(id);
    }

    //根据书籍名字查询书籍
    public Book findByName(String name) {
        return bookMapper.findByName(name);
    }

    //更新一本书籍信息
    public boolean updateOne(Book book) {
        int updateBookNum = bookMapper.updateOne(book);
        return updateBookNum == 1 ? true : false;
    }

    //删除一本书籍信息
    public boolean deleteOne(long id) {
        int deleteBookNum = bookMapper.deleteOne(id);
        if (deleteBookNum == 1) {
            bookPage.setItems(bookPage.getItems() - 1);       //书籍id数量减一
            return true;
        }
        return false;
    }

    //增加书籍信息
    public boolean insertOne(Book book) {
        int insertBookNum = bookMapper.insertOne(book);
        if (insertBookNum == 1) {
            bookPage.setItems(bookPage.getItems() + 1);
            return true;
        }
        return false;
    }


}
